package com.gomore.opple.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;

import com.gomore.opple.service.DownloadApkProcessor;
import com.gomore.opple.service.DownloadApkTask;
import com.gomore.opple.web.cgform.app.entity.TOAppversionEntity;
import com.gomore.opple.widgets.dialog.ConfirmDialog;
import com.gomore.opple.widgets.dialog.CustomProgressDialog;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class UpdateManager implements DownloadApkProcessor {
    private Activity context;

    private String versionName = "";

    private static final int DIALOG_NEED_UPDATE = 1;
    private static final int DIALOG_NONEED_UPDATE = 2;
    private static final int DIALOG_OPTION_UPDATE = 3;


    private boolean needReminder = false;
    private boolean isForceUpdate = false;
    private TOAppversionEntity mVersion;

    public CustomProgressDialog progressDialog; // 进度条对话框引用


    public ConfirmDialog confirmDialog;

    public UpdateManager(Activity context, boolean needReminder) {
        this.context = context;
        this.needReminder = needReminder;
        confirmDialog = new ConfirmDialog(context);
    }

    /**
     * 展示更新对话框
     *
     * @param version 服务器版本
     */
    public void displayUpdateDialog(TOAppversionEntity version) {
        if (version != null) {
            mVersion = version;
            versionName = version.getVersion();
            if (version.getForceupdate() != null) {
                if (version.getForceupdate().equals("1")) {
                    isForceUpdate = true;
                    showDialog(DIALOG_NEED_UPDATE);
                } else {
                    isForceUpdate = false;
                    showDialog(DIALOG_OPTION_UPDATE);
                }
            }
        } else {
            if (needReminder) {
                showDialog(DIALOG_NONEED_UPDATE);
            }
        }
    }

    private void showDialog(int id) {

        String title = "提示";
        String message = "";
        ConfirmDialog.onNoOnclickListener onNoOnclickListener = null;
        ConfirmDialog.onYesOnclickListener onYesOnclickListener = null;
        switch (id) {
            case DIALOG_NONEED_UPDATE:
                message = "已是最新版本，无需更新";
                onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        confirmDialog.dismiss();
                    }
                };
                break;
            case DIALOG_NEED_UPDATE:
                title = "有新版本,需要更新";
                message = "如不更新，当前版本将无法使用，新版本号：" + mVersion.getVersion();
                onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        confirmDialog.dismiss();
                        downLoadAPK();
                    }
                };
                onNoOnclickListener = new ConfirmDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        DialogUtils.cancel();
                        System.exit(0);
                    }
                };
                break;
            case DIALOG_OPTION_UPDATE:
                title = "有可更新版本，是否更新？";
                message = "新版本号：" + mVersion.getVersion();
                onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        confirmDialog.dismiss();
                        downLoadAPK();
                    }
                };
                onNoOnclickListener = new ConfirmDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        confirmDialog.dismiss();
                    }
                };
                break;
        }
        DialogUtils.showConfirmDialog(context, onYesOnclickListener, onNoOnclickListener, title, message);
    }


    public static int VersionComparison(String versionServer, String versionLocal) {
        String version1 = versionServer;
        String version2 = versionLocal;
        if (version1 == null || version1.length() == 0 || version2 == null
                || version2.length() == 0)
            throw new IllegalArgumentException("Invalid parameter!");

        int index1 = 0;
        int index2 = 0;
        while (index1 < version1.length() && index2 < version2.length()) {
            int[] number1 = getValue(version1, index1);
            int[] number2 = getValue(version2, index2);

            if (number1[0] < number2[0]) {
                return -1;
            } else if (number1[0] > number2[0]) {
                return 1;
            } else {
                index1 = number1[1] + 1;
                index2 = number2[1] + 1;
            }
        }
        if (index1 == version1.length() && index2 == version2.length())
            return 0;
        if (index1 < version1.length())
            return 1;
        else
            return -1;
    }

    /**
     * @param version
     * @param index   the starting point
     * @return the number between two dots, and the index of the dot
     */
    public static int[] getValue(String version, int index) {
        int[] value_index = new int[2];
        StringBuilder sb = new StringBuilder();
        while (index < version.length() && version.charAt(index) != '.') {
            sb.append(version.charAt(index));
            index++;
        }
        value_index[0] = Integer.parseInt(sb.toString());
        value_index[1] = index;

        return value_index;
    }

    public void downLoadAPK() {
        progressDialog = new CustomProgressDialog(context, false);
        progressDialog.setmMax(100);
        progressDialog.setCancelable(false);// 进度条不能回退
        progressDialog.setTitle("下载更新");// 设置标题
        progressDialog.show();

        String apkPath = context.getCacheDir() + "/" + versionName + ".apk";
        FileUtils.createNewFile(apkPath);

        DownloadApkTask downloadTask = new DownloadApkTask();
        downloadTask.setDownloadApkProcessor(this);
        downloadTask.execute(mVersion.getUrl(), apkPath);
    }

    @Override
    public void onDownloadCompleted(String filePath) {
        progressDialog.dismiss();
        if (filePath != null) {
            chmod("777", filePath);
            // 调用安装
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

            // 如果需要强制更新,下载完成后退出应用
            if (isForceUpdate) {
                System.exit(0);
            }
        }
    }

    @Override
    public void updateDownloadProgress(Integer progress, Integer total) {

        progressDialog.setProgress(progress, total);
    }

    @Override
    public void onDownloadFailed() {
        progressDialog.dismiss();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                System.exit(0);//登录页检查版本，下载失败退出app
            }
        }, 2 * 1000);


    }

    public void chmod(String permission, String path) {
        try {
            String command = "chmod " + permission + " " + path;
            Runtime runtime = Runtime.getRuntime();
            runtime.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}